package picture.dao;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import MyDaily.pojo.Picture;

@MultipartConfig(//
		fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
		maxFileSize = 1024 * 1024 * 50, // 50 MB
		maxRequestSize = 1024 * 1024 * 100 // 100 MB
)
@WebServlet("/addimg")
public class addimg extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 */
	private final static String WEB_APP_HOME_OF_TOMCAT = "/D:\\MyDaily\\src\\main\\webapp";

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 设置字符编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		Part filePart = request.getPart("file");
		String fileName = filePart.getSubmittedFileName();
		String path = null;
		String imgurl = null;
		if (!fileName.isEmpty()) {
			for (Part part : request.getParts()) {
				path = WEB_APP_HOME_OF_TOMCAT + "/img/";
				part.write(path + fileName);
			}
			// 获取图片路径
			imgurl = fileName;
			System.out.println(imgurl);
			// 获取用户名
			HttpSession session = request.getSession();
			String name = (String) session.getAttribute("name");
			// 获取系统时间
			Date day = new Date();
			Timestamp date = new Timestamp(day.getTime());
			//调用添加方法
			Picture pictur =new Picture();
			pictur.setName(name);
			pictur.setImgurl(imgurl);
			pictur.setDate(date);
			picture picture =new picture();
			int row = picture.Insertpicture(pictur);
			if (row > 0) {
				request.getRequestDispatcher("PiceterServlet").forward(request, response);
			}else {
				
			}
		} else {
			request.setAttribute("message", "文件上传失败！");
		}
	}
}
